//
//  DocumentLinkViewController.m
//  FMS
//
//  Created by Steven on 11/3/13.
//  Copyright (c) 2013 QGSVN. All rights reserved.
//

#import "DocumentLinkViewController.h"
#import "DetailedDocumentViewController.h"
#import "BuildingMgmtViewController.h"

@interface DocumentLinkViewController ()

@end

@implementation DocumentLinkViewController
@synthesize parent;
@synthesize currentDocumentDict;
@synthesize documentImage;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil parent:(id)_parent
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        dictLanguage = [ApplicationDelegate.arrayLanguage objectAtIndex:0];
        parent = _parent;
    }
    return self;
}

- (IBAction)backPreviousView:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)handleRightCornerEvent:(id)sender {
    BuildingMgmtViewController *controller = [[BuildingMgmtViewController alloc] initWithNibName:@"BuildingMgmtViewController" bundle:nil itemType:Building_Type];
    controller.parent = self;
//    controller.serviceType = [[dict objectForKey:@"serviceType"] intValue];
    
    [self.navigationController pushViewController:controller animated:NO];
}

- (BOOL) handleAddNewDocumentForItem:(NSMutableDictionary*)_itemDict {
    NSString *itemId = [_itemDict objectForKey:@"_id"];
    
    NSDate *today = [NSDate date];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *todayStr = [dateFormatter stringFromDate:today];
    
    NSString *imageUrl = [((DetailedDocumentViewController*)parent).documentDict objectForKey:@"imageUrl"];
    
    BOOL isExisted = NO;
    if ([CouchBaseLiteLib checkExistedItemByDocument:itemId documentLink:imageUrl]) {
        isExisted = YES;
        return isExisted;
    }
    
    //name for this document by today
    NSString *fileName = todayStr;
    
    NSMutableDictionary *photoDict = [NSMutableDictionary dictionaryWithObjectsAndKeys:todayStr,@"dateUploaded",imageUrl,@"imageUrl",itemId,@"itemId",DocumentAttachment,@"Table",fileName,@"fileName", nil];
    [photoDict setObject:[_itemDict objectForKey:@"item_name"] forKey:@"item_name"];
    [photoDict setObject:[_itemDict objectForKey:@"floor"] forKey:@"floor"];
    [photoDict setObject:[_itemDict objectForKey:@"building"] forKey:@"building"];
    [photoDict setObject:[_itemDict objectForKey:@"Table"] forKey:@"itemTable"];
    NSString *room = [_itemDict objectForKey:@"room"];
    if (room != nil)
        [photoDict setObject:room forKey:@"room"];
    
    NSError *error;
    [[CouchBaseLiteLib sharedCouchBaseLite] createDocumentWithAttachment:photoDict fileData:UIImageJPEGRepresentation(documentImage, 1.0) error:&error];
    if (!error) {
        [mainArray addObject:photoDict];
        [_mainTableView reloadData];
    }
    
    return isExisted;
}

- (void) listItemsByDocument {
    [mainArray removeAllObjects];
    currentRecordIndex = 0;
    
    if (!isLock) {
//        dispatch_queue_t myQueue = dispatch_queue_create("com.myqgs.listMoreInspection", NULL);
//        dispatch_async(myQueue, ^(void) {
            isLock = YES;
            NSMutableArray *tmpArray = [NSMutableArray arrayWithCapacity:1];
            
            tmpArray = [CouchBaseLiteLib listItemsByDocument:[((DetailedDocumentViewController*)parent).documentDict objectForKey:@"imageUrl"] from:currentRecordIndex numberRow:NUMBER_ROW_PAGE];
            
            for (int i=0;i < [tmpArray count];i++) {
                NSMutableDictionary *dict = [[tmpArray objectAtIndex:i] mutableCopy];
                CBLDocument *itemDoc = [CouchBaseLiteLib getDocumentById:[dict objectForKey:@"itemId"]];
                NSString *table = [itemDoc propertyForKey:@"Table"];

                if (itemDoc.properties != nil) {
                    if ([table isEqualToString:BuildingMgmtDoc])
                        [dict setObject:[itemDoc propertyForKey:@"item_name"] == nil ? [itemDoc propertyForKey:@"roomName"] : [itemDoc propertyForKey:@"item_name"] forKey:@"item_name"];
                    else
                        [dict setObject:[itemDoc propertyForKey:@"item_name"] == nil ? [itemDoc propertyForKey:@"name"] : [itemDoc propertyForKey:@"item_name"] forKey:@"item_name"];
                    [dict setObject:[itemDoc propertyForKey:@"floor"] forKey:@"floor"];
                    [dict setObject:[itemDoc propertyForKey:@"building"] forKey:@"building"];
                    [dict setObject:[itemDoc propertyForKey:@"Table"] forKey:@"itemTable"];
                    NSString *room = [itemDoc propertyForKey:@"room"];
                    if (room != nil)
                        [dict setObject:room forKey:@"room"];
                    
                    [mainArray addObject:dict];
                }
                else {
                    //remove document which link with this item
                    NSError *error;
                    [[CouchBaseLiteLib sharedCouchBaseLite] deleteDocumentById:[dict objectForKey:@"_id"] error:&error];
                }
            }
            
//            dispatch_async(dispatch_get_main_queue(), ^(void) {
                [_mainTableView reloadData];
                
                currentRecordIndex += [tmpArray count];
                
                if ([tmpArray count] == NUMBER_ROW_PAGE) {
                    isLoadMore = YES;
                }
                else {
                    isLoadMore = NO;
                }
                
                [self.mainTableView reloadData];
                
                isLock = NO;
                
                if (isLoadMore) {
                    [self.mainTableView showLoadingMore];
                }
                else
                    [self.mainTableView hideLoadingMore];
                [self.mainTableView hideActivity];
//            });
//        });
#if !OS_OBJECT_USE_OBJC
//        dispatch_release(myQueue);
#endif
//        myQueue = nil;
    }
}

- (void) listMoreItemsByDocument {
    if (!isLock) {
//        dispatch_queue_t myQueue = dispatch_queue_create("com.myqgs.listMoreInspection", NULL);
//        dispatch_async(myQueue, ^(void) {
            isLock = YES;
            NSMutableArray *tmpArray = [NSMutableArray arrayWithCapacity:1];
            
            tmpArray = [CouchBaseLiteLib listItemsByDocument:[((DetailedDocumentViewController*)parent).documentDict objectForKey:@"imageUrl"] from:currentRecordIndex numberRow:NUMBER_ROW_PAGE];
            
            for (int i=0;i < [tmpArray count];i++) {
                NSMutableDictionary *dict = [[tmpArray objectAtIndex:i] mutableCopy];
                CBLDocument *itemDoc = [CouchBaseLiteLib getDocumentById:[dict objectForKey:@"itemId"]];
                NSString *table = [itemDoc propertyForKey:@"Table"];
                
                if (itemDoc.properties != nil) {
                    if ([table isEqualToString:BuildingMgmtDoc])
                        [dict setObject:[itemDoc propertyForKey:@"item_name"] == nil ? [itemDoc propertyForKey:@"roomName"] : [itemDoc propertyForKey:@"item_name"] forKey:@"item_name"];
                    else
                        [dict setObject:[itemDoc propertyForKey:@"item_name"] == nil ? [itemDoc propertyForKey:@"name"] : [itemDoc propertyForKey:@"item_name"] forKey:@"item_name"];
                    [dict setObject:[itemDoc propertyForKey:@"floor"] forKey:@"floor"];
                    [dict setObject:[itemDoc propertyForKey:@"building"] forKey:@"building"];
                    [dict setObject:[itemDoc propertyForKey:@"Table"] forKey:@"itemTable"];
                    NSString *room = [itemDoc propertyForKey:@"room"];
                    if (room != nil)
                        [dict setObject:room forKey:@"room"];
                    
                    [mainArray addObject:dict];
                }
                else {
                    //remove document which link with this item
                    NSError *error;
                    [[CouchBaseLiteLib sharedCouchBaseLite] deleteDocumentById:[dict objectForKey:@"_id"] error:&error];
                }
            }
            
//            dispatch_async(dispatch_get_main_queue(), ^(void) {
                int previousIndex = currentRecordIndex;
                currentRecordIndex += [tmpArray count];
            
                if ([tmpArray count] == NUMBER_ROW_PAGE) {
                    isLoadMore = YES;
                }
                else {
                    isLoadMore = NO;
                }
                
                NSMutableArray *indexPaths = [[NSMutableArray alloc] init];
                for (int i=previousIndex;i < currentRecordIndex;i++) {
                    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];
                    [indexPaths addObject:indexPath];
                }
                if ([indexPaths count] > 0) {
                    [self.mainTableView insertRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationAutomatic];
                }
                
                isLock = NO;
                
                if (isLoadMore) {
                    [self.mainTableView showLoadingMore];
                }
                else
                    [self.mainTableView hideLoadingMore];
                [self.mainTableView hideActivity];
//            });
//        });
#if !OS_OBJECT_USE_OBJC
//        dispatch_release(myQueue);
#endif
//        myQueue = nil;
    }
}

- (void) viewDidLoad {
    [super viewDidLoad];
    self.navigationController.navigationBar.hidden = YES;
    
    _mainTableView.layer.borderColor = APPLE_BLUE_COLOR.CGColor;
    _mainTableView.layer.borderWidth = 1;
    
    _mainTableView.separatorColor = APPLE_BLUE_COLOR;
    
    mainArray = [NSMutableArray arrayWithCapacity:1];
    
    [self listItemsByDocument];
}

#pragma mark scrollview load more
- (void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView{
    didReadyLoadMore = NO;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    float bottomEdge = scrollView.contentOffset.y + scrollView.frame.size.height;
    if (bottomEdge >= scrollView.contentSize.height && !didReadyLoadMore)
    {
        didReadyLoadMore = YES;
        
        if(!isLoadMore)
        {
            [self.mainTableView hideLoadingMore];
            return;
        }
        [self.mainTableView showActivity];
        [self listMoreItemsByDocument];
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    return [mainArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    //    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
    
    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    // Configure the cell...
    NSMutableDictionary *dict = [mainArray objectAtIndex:indexPath.row];
    
    UILabel *lbItemId = [[UILabel alloc] initWithFrame:CGRectMake(19, 7.5, 210, 21)];
    lbItemId.backgroundColor = [UIColor clearColor];
    lbItemId.text = [dict objectForKey:@"item_name"];
    [cell.contentView addSubview:lbItemId];
    
    UILabel *lbRoom = [[UILabel alloc] initWithFrame:CGRectMake(261, 7.5, 150, 21)];
    lbRoom.backgroundColor = [UIColor clearColor];
    lbRoom.text = [dict objectForKey:@"room"] == nil ? [dict objectForKey:@"item_name"] : [dict objectForKey:@"room"];
    [cell.contentView addSubview:lbRoom];
    
    UILabel *lbFloor = [[UILabel alloc] initWithFrame:CGRectMake(444, 7.5, 100, 21)];
    lbFloor.backgroundColor = [UIColor clearColor];
    lbFloor.text = [dict objectForKey:@"floor"];
    [cell.contentView addSubview:lbFloor];
    
    UILabel *lbBuilding = [[UILabel alloc] initWithFrame:CGRectMake(586, 7.5, 150, 21)];
    lbBuilding.backgroundColor = [UIColor clearColor];
    lbBuilding.text = [dict objectForKey:@"building"];
    [cell.contentView addSubview:lbBuilding];
    
    UILabel *lbItemType = [[UILabel alloc] initWithFrame:CGRectMake(770, 7.5, 150, 21)];
    lbItemType.backgroundColor = [UIColor clearColor];
    [cell.contentView addSubview:lbItemType];
    
    NSString *table = [dict objectForKey:@"itemTable"];
    if ([table isEqualToString:BuildingMgmtDoc]) {
        lbItemId.text = @"-";
        lbItemType.text = [dictLanguage objectForKey:@"schedule.title-building"];
    }
    else {
        lbItemType.text = [dictLanguage objectForKey:@"schedule.title-facility"];
    }
    
//    cell.userInteractionEnabled = NO;
    
    return cell;
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    NSMutableDictionary *dict = [mainArray objectAtIndex:indexPath.row];
    
    BOOL isSameItem = NO; //check if current selected item is deleted item
    NSString *selectedItem = [currentDocumentDict objectForKey:@"_id"];
    if ([selectedItem isEqualToString:[dict objectForKey:@"_id"]])
        isSameItem = YES;
    //get document of this row
    NSError *error;
    [[CouchBaseLiteLib sharedCouchBaseLite] deleteDocumentById:[dict objectForKey:@"_id"] error:&error];
    if (!error) {
        [mainArray removeObjectAtIndex:indexPath.row];
        //reload table
        NSMutableArray *indexPathArray = [NSMutableArray arrayWithObjects:indexPath, nil];
        [_mainTableView deleteRowsAtIndexPaths:indexPathArray withRowAnimation:UITableViewRowAnimationAutomatic];
        
        //reload grand view
        [(DetailedDocumentViewController*)parent reloadGrandView];
        
        //if deleted item is current selected item
        if (isSameItem)
            [self dismissViewControllerAnimated:YES completion:^(void) {
                //do something
            }];
    }
    else {
        UIAlertView *dialog = [[UIAlertView alloc] initWithTitle:[dictLanguage objectForKey:@"gereral.warning"] message:@"Delete document failed. Please try again" delegate:Nil cancelButtonTitle:[dictLanguage objectForKey:@"general.ok"] otherButtonTitles:nil];
        [dialog show];
    }
}

@end
